package com.jcxh.sg_exam.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jcxh.sg_exam.pojo.Danxuan;
import com.jcxh.sg_exam.pojo.Duoxuan;
import com.jcxh.sg_exam.pojo.Panduan;
import com.jcxh.sg_exam.pojo.Result;
import com.jcxh.sg_exam.pojo.dto.AddPanduanDto;
import com.jcxh.sg_exam.pojo.dto.PanduanDto;
import com.jcxh.sg_exam.service.PanduanService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author 鹏少
 * @Date 2024/8/9
 * @Date 9:59
 */
@Api(tags = "判断类接口")
@RestController
@RequestMapping("/admin")
@Slf4j
public class PanduanController {

    @Autowired
    private PanduanService panduanService;

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("判断类别查询")
    @GetMapping("/getPanDuanType")
    public Result getType() {
        try {
            List<Panduan> duoxuanList = panduanService.lambdaQuery().getBaseMapper().selectList(null);
            Set<String> collect = duoxuanList.stream()
                    .map(Panduan::getType)
                    .collect(Collectors.toSet());
            return Result.success(collect);
        } catch (Exception e) {
            // 记录日志
            log.error("获取类别时发生异常", e);
            // 返回通用错误信息
            return Result.error("获取类别失败，请稍后再试。");
        }
    }


    @ApiOperation(value = "判断考题查询")
    @GetMapping("/getPanduan")
    public Result getPanduan(
            @ApiParam(value = "当前页码", required = true) @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
            @ApiParam(value = "每页大小(后端默认是10)", required = true) @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @ApiParam(value = "类别(默认查询全部)") String type,
            @ApiParam(value = "题目") String title) {

        IPage<Panduan> page = new Page<>(currentPage, pageSize);

        IPage<Panduan> panduanPage = panduanService.lambdaQuery()
                .eq(type != null, Panduan::getType, type)
                .like(title != null, Panduan::getTitle, title)
                .orderByAsc(Panduan::getId).page(page);
        return Result.success(panduanPage);

    }

    @ApiOperation(value = "根据判断题id查询判断题信息")
    @GetMapping("/selectPanduan")
    public Result selectPanduan(@ApiParam(value = "判断考题id", required = true) Integer id) {

        Panduan panduan = panduanService.lambdaQuery().eq(Panduan::getId, id).one();

        return Result.success(panduan);

    }


    @ApiOperation(value = "判断考题修改按钮")
    @PutMapping("/updatePanduan")
    public Result updatePanduan(@ApiParam(value = "判断实体类", required = true)
                                @Valid @RequestBody PanduanDto panduanDto, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            // 如果有验证错误，返回具体的错误信息
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
//            String errorMessages = fieldErrors.stream()
//                    .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
//                    .collect(Collectors.joining(", "));
            String errorMessages = fieldErrors.stream()
                    .map(fieldError -> fieldError.getDefaultMessage())
                    .collect(Collectors.joining(", "));
            return Result.error("验证失败：" + errorMessages);
        }
        boolean flag = panduanService.lambdaUpdate()
                .set(panduanDto.getTitle() != null, Panduan::getTitle, panduanDto.getTitle())
                .set(panduanDto.getAnswer() != null, Panduan::getAnswer, panduanDto.getAnswer())
                .set(panduanDto.getType() != null, Panduan::getType, panduanDto.getType())
                .set(panduanDto.getAnalysis() != null, Panduan::getAnalysis, panduanDto.getAnalysis())
                .eq(panduanDto.getId() != null, Panduan::getId, panduanDto.getId()).update();


        // 清空 Redis 中的 List
        redisTemplate.delete("panDuan");

        // 从数据库中获取数据并存入 Redis
        List<Panduan> panduanList = panduanService.lambdaQuery().list();
        redisTemplate.opsForList().rightPushAll("panDuan", panduanList);
        if (flag) {
            return Result.success("修改成功");

        } else {
            return Result.error("修改失败");
        }

    }

    @ApiOperation(value = "判断考题删除按钮")
    @DeleteMapping("/deletePanduan")
    public Result deleteDuoxuan(@ApiParam(value = "要删除判断题的id", required = true) @RequestParam(required = true) List<Integer> ids) {

        if (ids.size() == 0) {
            return Result.error("请勾选要删除的考题");
        }
        boolean removeByIds = panduanService.removeByIds(ids);
        // 清空 Redis 中的 List
        redisTemplate.delete("panDuan");

        // 从数据库中获取数据并存入 Redis
        List<Panduan> panduanList = panduanService.lambdaQuery().list();
        log.info("--------{}",panduanList);
        redisTemplate.opsForList().rightPushAll("panDuan", panduanList);
        if (removeByIds) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }

    }

    @ApiOperation(value = "新增判断考题按钮")
    @PostMapping("/addPanduan")
    public Result addPanduan(@ApiParam(value = "新增判断考题dto")
                             @Valid @RequestBody AddPanduanDto panduanDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            // 如果有验证错误，返回具体的错误信息
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
//            String errorMessages = fieldErrors.stream()
//                    .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
//                    .collect(Collectors.joining(", "));
            String errorMessages = fieldErrors.stream()
                    .map(fieldError -> fieldError.getDefaultMessage())
                    .collect(Collectors.joining(", "));
            return Result.error("验证失败：" + errorMessages);
        }
        Panduan panduan = new Panduan();
        BeanUtils.copyProperties(panduanDto, panduan);
        panduan.setOptionA("正确");
        panduan.setOptionA("错误");
        boolean save = panduanService.save(panduan);

        // 清空 Redis 中的 List
        redisTemplate.delete("panDuan");

        // 从数据库中获取数据并存入 Redis
        List<Panduan> panduanList = panduanService.lambdaQuery().list();
        redisTemplate.opsForList().rightPushAll("panDuan", panduanList);
        if (save) {
            return Result.success("添加判断考题成功");
        } else {
            return Result.error("添加判断考题失败");
        }

    }


}
